//
//  FPHomeAndMeBaseController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/2/24.
//

#import "FPHomeAndMeBaseController.h"
#import "FPLoginController.h"
#import "FPHomePageController.h"
#import "FPMeViewController.h"


@interface FPHomeAndMeBaseController () <PrivacyDidTapDelegate , UITextFieldDelegate>

@property (nonatomic , assign) NSInteger timeOut;

@end

@implementation FPHomeAndMeBaseController

LazyLoadDataSource(protocolSource);

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if (self.showLoginWindow) {
        
        [self loginAction];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (UIDevice.safeDistanceTop == 20) {
        
        self.tableView.contentInset = UIEdgeInsetsMake(-12, 0, 0, 0);  // 64 是状态栏的高度
        self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    }
    
    [self getProtocolShowLoginView:NO];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    // 自动恢复TabBar显示（如果当前页面是TabBar的子页面）
    if ([self isKindOfClass:[FPHomePageController class]] || [self isKindOfClass:[FPMeViewController class]]) {
        if (self.hideTabBar) {
            self.hideTabBar = NO;
            [self setTabBarHidden];
        }
        
        // 强制确保TabBar可见
        [self ensureTabBarVisible];
    }
}

#pragma mark - 确保TabBar可见
- (void)ensureTabBarVisible {
    if (self.tabBarController && self.tabBarController.tabBar) {
        // 确保TabBar不是隐藏状态
        self.tabBarController.tabBar.hidden = NO;
        self.tabBarController.tabBar.alpha = 1.0;
    }
}

#pragma mark - 处理隐私协议弹窗里面的 协议点击事件
- (void)customViewDidTapPrivacy:(FPProtocolModel *)model {
    
    [self.view endEditing:YES];
    
    self.showLoginWindow = YES;
    [self dismissPopup];
    
    FPMainWebController *vc = [[FPMainWebController alloc] init];
    
    vc.model = model;
    vc.userPanGestureInvalid = YES;
    vc.protocolType = FPProtocolTypeLogin;
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)dismissPopup {
    
    [self.loginView hidePopup];
    self.hideTabBar = NO;
    [self performSelector:@selector(setTabBarHidden) withObject:nil afterDelay:.05f];
}

- (void)setTabBarHidden {
    
    BOOL hidden = self.hideTabBar;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGRect frame = self.tabBarController.tabBar.frame;

    if (hidden) {
        frame.origin.y = screenHeight; // 移动 TabBar 到屏幕外
    } else {
        frame.origin.y = screenHeight - frame.size.height; // 恢复 TabBar
    }
    
    self.tabBarController.tabBar.frame = frame;
    
    [UIView animateWithDuration:0.25f animations:^{
        self.tabBarController.tabBar.frame = frame;
    } completion:^(BOOL finished) {
    }];
}


#pragma mark - 获取协议
- (void)getProtocolShowLoginView:(BOOL)showLoginView {
    
    [FPProtocolModel getProtocolWithType:(FPProtocolTypeLogin) success:^(NSInteger code, NSString * _Nonnull message, NSArray *list) {
        [MBManager hideLoading];
        
        [self.protocolSource removeAllObjects];
        if (code == 200) {
            
            for (FPProtocolModel *model in list) {
                
                [self.protocolSource addObject:model];
            }
            
            if (showLoginView) {
                
                self.showLoginWindow = NO;
                
                // 创建弹窗视图实例
                self.loginView = [[FPLoginView alloc] initWithSource:self.protocolSource];
                self.loginView.delegate = self;
                self.hideTabBar = YES;
                [self performSelector:@selector(showLoginView) withObject:nil afterDelay:.05f];
                [self setTabBarHidden];
            }
        }
        
    } failure:^(NSError * _Nonnull error) {
        [MBManager hideLoading];
    }];
}

#pragma mark - 登录
- (void)loginAction {
    
    if (self.protocolSource.count == 0) {
        
        [MBManager showLoading];
        [self getProtocolShowLoginView:NO];
        return;
    }
    
    self.showLoginWindow = NO;
    
    // 创建弹窗视图实例
    self.loginView = [[FPLoginView alloc] initWithSource:self.protocolSource];
    self.loginView.delegate = self;
    self.hideTabBar = YES;
    [self performSelector:@selector(showLoginView) withObject:nil afterDelay:.05f];
    [self setTabBarHidden];
}

#pragma mark - 显示登录弹窗
- (void)showLoginView {
    
//    [self.view addSubview:self.loginView];
    UIWindow *keyWindow = [UIApplication sharedApplication].windows.firstObject;
    [keyWindow addSubview:self.loginView];
//
//    [IQKeyboardManager sharedManager].enable = YES;
//    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
    // 显示弹窗
    [self.loginView showPopup];
    
    self.loginView.popupView.phoneTF.delegate = self;
    self.loginView.popupView.codeTF.delegate = self;
    
    if (self.phoneNumber) {
        
        self.loginView.popupView.phoneTF.text = self.phoneNumber;
    }
    
//    if (self.SMSCode) {
//
//        self.loginView.popupView.codeTF.text = self.SMSCode;
//    }
    
    WeakSelf;
    self.loginView.getSMSCodeBlock = ^{
      
        [weakSelf getSMSCode];
    };
    
    self.loginView.loginBlock = ^void{
        
        [weakSelf login];
    };
    
    self.loginView.showTabBarBlock = ^{
        
        [weakSelf dismissPopup];
    };
    
    [self.loginView.popupView.loginBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
       
        [self login];
    }];
    
    // 监听键盘显示与隐藏
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
}

// 键盘显示时调整弹窗位置
- (void)keyboardWillShow:(NSNotification *)notification {
    // 获取键盘的高度
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = keyboardFrame.size.height;
    
    // 获取当前弹窗的位置
    CGRect popUpFrame = self.loginView.frame;
    
    // 移动弹窗，避免与键盘重叠
    popUpFrame.origin.y = SCREEN_HEIGHT - keyboardHeight - popUpFrame.size.height + (self.loginView.popupView.height - self.loginView.popupView.lineView2.bottom);
    self.loginView.frame = popUpFrame;
}

// 键盘隐藏时恢复弹窗位置
- (void)keyboardWillHide:(NSNotification *)notification {
    // 恢复弹窗位置
    CGRect popUpFrame = self.loginView.frame;
    popUpFrame.origin.y = self.view.frame.size.height - popUpFrame.size.height + UIDevice.tabBarFullHeight;
    self.loginView.frame = popUpFrame;
}

#pragma mark - 获取验证码
- (void)getSMSCode {
    
    if (self.loginView.popupView.phoneTF.text.length != 11) {
        
        FeedBackGeneratorAction
        [self.loginView.popupView.phoneTF shake];
        return;
    }
    
    self.phoneNumber = self.loginView.popupView.phoneTF.text;
    
    NSString *number = [FPUserModel AES256Encrypt:self.phoneNumber];
    
    [MBManager showLoading];
    [FPUserModel getMessageCodeWithPhoneNumber:number success:^(BOOL isSuccess, NSString * _Nonnull message, NSInteger code) {
        [MBManager hideLoading];
        
        if (code == 200) {
            
            [self startCountDownTimer];
        }
        else {
            
            [self showText:message];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

#pragma mark - 登录
- (void)login {
    
    if (self.phoneNumber.length != 11) {
        
        FeedBackGeneratorAction
        [self.loginView.popupView.phoneTF shake];
        return;
    }
    
    if ([NSString isBlankString:self.SMSCode]) {
        
        FeedBackGeneratorAction
        [self.loginView.popupView.codeTF shake];
        return;
    }
    
    if (self.loginView.isSelect == NO) {
        
        [self.loginView shakePrivacyView];
        return;
    }
    
    NSString *number = [FPUserModel AES256Encrypt:self.phoneNumber];
    
    [MBManager showLoading];
    [FPUserModel loginWithPhoneNumber:number code:self.SMSCode success:^(FPUserModel * _Nonnull model, NSString * _Nonnull message, NSInteger code , BOOL firstRegistered) {
        [MBManager hideLoading];
        
        if (code == 200) {
            
//            [self showText:@"登录成功"];
            self.loginView.popupView.phoneTF.text = @"";
            self.phoneNumber = @"";
            [self dismissPopup];
            
//            self.loginSuccessBlock();
            
//            [self refreshData];
            self.timeOut = 1;
            [[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessNotification object:@(self.controllerType)];
            [self signProtocolWithParams:self.protocolSource];
        }
        else {
            
            [self showText:message];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

#pragma mark - 开始倒计时 验证码
- (void)startCountDownTimer {
    
    NSDate *oldDate = [NSDate date];
    // 倒计时时间
    self.timeOut = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        
        // 倒计时结束
        if (self.timeOut <= 0) {
            
            // 再次获取
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.loginView.popupView.getCodeBtn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
                self.loginView.popupView.getCodeBtn.userInteractionEnabled = YES;
                self.loginView.popupView.getCodeBtn.enabled = YES;
                [self.loginView.popupView.getCodeBtn setTitleColor:MAIN_BLUE_COLOR forState:(UIControlStateNormal)];
            });
        }
        // 正在倒计时
        else {
            
            NSDate *newDate = [NSDate date];
            NSTimeInterval timeInterva = [newDate timeIntervalSinceDate:oldDate];
            int seconds2 = (60 -timeInterva);
            NSString *timeStr = [NSString stringWithFormat:@"%d",seconds2];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.loginView.popupView.getCodeBtn setTitle:[NSString stringWithFormat:@"重新获取(%@)", timeStr] forState:UIControlStateNormal];
                self.loginView.popupView.getCodeBtn.userInteractionEnabled = NO;
                self.loginView.popupView.getCodeBtn.enabled = NO;
                [self.loginView.popupView.getCodeBtn setTitleColor:[UIColor hexColor:@"#999999"] forState:(UIControlStateNormal)];
            });
            //bug 解决
            if (seconds2 <= 1) {
                self.timeOut = 1;
            }
            self.timeOut--;
        }
    });
    dispatch_resume(_timer);
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if ([string isEqualToString:@""]) {
        
        return YES;
    }
    
    if ([textField isEqual:self.loginView.popupView.phoneTF]) {
        
        return textField.text.length < 11;
    }
    
    if ([textField isEqual:self.loginView.popupView.codeTF]) {
        
        return textField.text.length < 4;
    }
    
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    if ([textField isEqual:self.loginView.popupView.phoneTF]) {
        
        self.phoneNumber = self.loginView.popupView.phoneTF.text;
    }
    else if ([textField isEqual:self.loginView.popupView.codeTF]) {
        
        self.SMSCode = self.loginView.popupView.codeTF.text;
    }
}

@end
